package com.shangcheng.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shangcheng.entity.TProduct;
import com.shangcheng.entity.TShopCart;
import com.shangcheng.mapper.TProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductServiceImpl {
    @Autowired
    private TProductMapper productDao;
    @Transactional
    public TProduct addProduct(TProduct product) {
        productDao.insert(product);
        return product;
    }
    @Transactional(readOnly = true)
    public List<TProduct> allProducts() {
        return productDao.selectList(null);
    }

    @Transactional(readOnly = true)
    public Page<TProduct> pageProducts(int page, int size) {
        Page<TProduct> pagination = new Page<>(page, size); // 创建分页对象
        return productDao.selectPage(pagination, null); // 查询分页数据
    }


    @Transactional(readOnly = true)
    public List<TProduct> searchProducts(String query) {
        return productDao.selectList(new QueryWrapper<TProduct>()
                .like("name", query)); // 仅根据商品名称搜索
    }


//    @Transactional(readOnly = true)
//    public List<TProduct> getProductsByCategory(Integer categoryId) {
//        return productDao.selectList(new QueryWrapper<TProduct>()
//                .eq("cate_id", categoryId));
//    }
    //按类分页查
    @Transactional(readOnly = true)
    public Page<TProduct> pageProductsByCategory(Integer categoryId, int pageNum, int pageSize) {
        Page<TProduct> page = new Page<>(pageNum, pageSize);
        return productDao.selectPage(page, new QueryWrapper<TProduct>().eq("CATE_ID", categoryId));
    }

    // 新增：按关键词和分类搜索商品
    @Transactional(readOnly = true)
    public List<TProduct> searchProductsByCategory(String query, Integer categoryId) {
        return productDao.selectList(new QueryWrapper<TProduct>()
                .like("name", query)
                .eq("cate_id", categoryId));
    }

    // 根据商品id获取商品详细信息
    @Transactional(readOnly = true)
    public TProduct getProductById(Integer id) {
        return productDao.selectById(id);
    }
    //删除商品
    @Transactional()
    public  void deletProduct(Long productId) {
        productDao.delete(new QueryWrapper<TProduct>().eq("ID", productId));

    }

}
